package com.voice.core.api.utils;

import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.function.BiConsumer;

public class HttpCommonUtil {


    public static <T,U> void mapConsume(Map<T, U> params,BiConsumer<Boolean, Map.Entry<T,U>> consumer){
        if (null != params && params.size() > 0) {
            Iterator iterator = params.entrySet().iterator();
            boolean isFirst = true;
            while (iterator.hasNext()) {
                Map.Entry<T,U> entry = (Map.Entry) iterator.next();
                consumer.accept(isFirst, entry);
                if(isFirst) isFirst=false;
            }
        }
    }

    public static String buildParamString(Map<String, String> params) {
        StringBuilder result = new StringBuilder();
        mapConsume(params,(isFirst,entry)->{
            if (!isFirst) result.append("&");
            result.append(entry.getKey()).append("=").append(entry.getValue());
        });
        return result.toString();
    }

    public static String buildSignParamString(Map<String, String> params) {
        StringBuilder result = new StringBuilder();
        mapConsume(params,(isFirst,entry)->{
            if (!isFirst) result.append("&");
            result.append(entry.getKey());
            if(!StringUtils.isEmpty(entry.getValue())){
                result.append("=").append(entry.getValue());
            }
        });
        return result.toString();
    }

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isEmpty(byte[] array) {
        return array == null || array.length == 0;
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }

}
